using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesCreateNew : System.Web.UI.Page
{
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;

    #region response text
    public string Response_Error
    {
        get
        {
            return ViewState["Response_Error"].ToString();
        }

        set
        {
            ViewState["Response_Error"] = value;
        }
    }

    public string ValidatePurpose
    {
        get
        {
            return ViewState["ValidatePurpose"].ToString();
        }

        set
        {
            ViewState["ValidatePurpose"] = value;
        }
    }

    public string ValidateCategory
    {
        get
        {
            return ViewState["ValidateCategory"].ToString();
        }

        set
        {
            ViewState["ValidateCategory"] = value;
        }
    }

    public string GeneralClaim
    {
        get
        {
            return ViewState["GeneralClaim"].ToString();
        }

        set
        {
            ViewState["GeneralClaim"] = value;
        }
    }

    public string EntertainmentClaim
    {
        get
        {
            return ViewState["EntertainmentClaim"].ToString();
        }

        set
        {
            ViewState["EntertainmentClaim"] = value;
        }
    }

    //public string PACEMarketingEventClaim
    //{
    //    get
    //    {
    //        return ViewState["PACEMarketingEventClaim"].ToString();
    //    }

    //    set
    //    {
    //        ViewState["PACEMarketingEventClaim"] = value;
    //    }
    //}

    public string WarningMessage
    {
        get
        {
            return ViewState["WarningMessage"].ToString();
        }

        set
        {
            ViewState["WarningMessage"] = value;
        }
    }
    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();    // first thing to do for every page

        this.Table_MessageBox.Visible = false;

        if (!IsPostBack)
        {
            this.PageComponentSetup();
            this.SwitchLanguage();
            TextBox_DefaultProjectID.Attributes.Add("onclick", "javascript:ShowModal('ProjectBrowser', this, '?id=" + this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID + "'); return false;");
        }

        this.GenerateExchangeRate();
        this.GenerateCountryCurrencyRefference();
        this.GenerateWarningMessage();
    }
    #endregion

    #region Button_Submit_Click
    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        bool smooth = true;        
        string ClaimInternalID = "";

        if (this.DataValidate())
        {
            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                GonzalesClaimHeader CurClaimHeader = new GonzalesClaimHeader();

                CurClaimHeader.Reasons = this.TextBox_Purpose.Text;
                CurClaimHeader.CreatedOn = DateTime.Now;
                CurClaimHeader.Status = GonzalesClaimHeader.TypeOfClaimStatus.Draft;
                CurClaimHeader.LastUpdatedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                CurClaimHeader.LastUpdatedOn = DateTime.Now; // When we setup shortdatetime is format: dd/MM/yyyy in system --> Ezy-Claims have error
                CurClaimHeader.ClaimedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                CurClaimHeader.CompanyClaimedFrom = this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany;
                CurClaimHeader.LocalCurrency = this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency;
                CurClaimHeader.Category = ClaimManager.GetClaimCategoryFromCode(this.RadioButtonList_Category.SelectedValue);

                CurClaimHeader.DefaultCountryCode = this.DropDownList_DefaultCountry.SelectedValue;
                CurClaimHeader.DefaultCurrencyCode = this.DropDownList_DefaultCurrency.SelectedValue;
                CurClaimHeader.DefaultExchangeRate = decimal.Parse(this.TextBox_DefaultCurrencyRate.Text);
                // Thang Nguyen added 25/03/2013
                if (this.RadioButtonList_Category.SelectedValue.Equals("2")) CurClaimHeader.DefaultProjectID = this.TextBox_DefaultProjectID.Text.Trim();

                //added by agnes[01042009] - enhancement. Need to check the exchange rate which more than +- 5%. pop up message.
                //get the latest exchange rate first.
                //after that do the comparison with the created exchange rate. find out the difference

                if (CurClaimManager.CreateNewClaim(CurClaimHeader))
                {
                    smooth = true;
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesCreateNew.Button_Submit_Click] : Failed at CurClaimManager.CreateNewClaim() : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.Response_Error.Replace("#ID#", LogID));
                }

                ClaimInternalID = CurClaimHeader.InternalID;

            }

            if (smooth)
            {
                // this is to monitor entire claim flow
                this.CurLogManager.LogAction(ClaimInternalID, this.CurrentPrivateSession.ActualLoginUser.InternalID, GonzalesUserAction.ClaimCreated, GonzalesClaimHeader.TypeOfClaimStatus.Submitted);

                string ResponseRedirect = "";

                ResponseRedirect = ((this.CheckBox_ImportCreditCard.Checked) ? "GonzalesCCImport.aspx" : "GonzalesMyDraftDetail.aspx") + "?id=" + ClaimInternalID;
                Response.Redirect(ResponseRedirect);
            }
        }

    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        this.LabelValue_EmployeeID.Text = this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID;
        this.LabelValue_Name.Text = this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName;
        this.LabelValue_ProfitCenter.Text = this.CurrentPrivateSession.CurrentLoggedOnUser.CostCenter;

        this.CheckBox_ImportCreditCard.Checked = (this.CurrentPrivateSession.CurrentLoggedOnUser.CreditCardNo.Length == 16);
        this.CheckBox_ImportCreditCard.Visible = false;

        string SelectedCurrency = "";

        this.DropDownList_DefaultCountry.Attributes["OnChange"] = "CountryOnChange(this);";
        this.DropDownList_DefaultCurrency.Attributes["OnChange"] = "CurrencyOnChange(this);";
        this.Button_Submit.Attributes["onclick"] = "return ExchangeRateOnChange();";

        // Country
        using (CountryManager CurManager = new CountryManager(this.CurrentPrivateSession))
        {
            MasterBaseCollection ResultCollection = CurManager.GetAllCountry();
            if (ResultCollection != null)
            {
                int i = 0;

                this.DropDownList_DefaultCountry.Items.Clear();
                foreach (MasterBase CountryObj in ResultCollection)
                {
                    Country CurCountryObj = (Country)CountryObj;                    

                    this.DropDownList_DefaultCountry.Items.Add(new ListItem(CountryObj.DisplayName, CountryObj.InternalID));
                    this.DropDownList_DefaultCountry.Items[i].Attributes["title"] = CountryObj.DisplayName;
                    i++;

                    if (CountryObj.InternalID.CompareTo(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.FromCountry.InternalID) == 0)
                    {
                        SelectedCurrency = CurCountryObj.CountryCurrency.InternalID;
                        this.DropDownList_DefaultCountry.Items[(this.DropDownList_DefaultCountry.Items.Count - 1)].Selected = true;
                    }
                }
            }
        }

        // Currency / Exchange Rate
        using (CurrencyManager CurManager = new CurrencyManager(this.CurrentPrivateSession))
        {
            MasterBaseCollection ResultCollection = CurManager.GetAllCurrency();
            MasterBaseCollection ExRateCollection = CurManager.GetLatestExchangeRate(this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency);

            if (ResultCollection != null)
            {
                this.DropDownList_DefaultCurrency.Items.Clear();
                foreach (MasterBase CurrencyObj in ResultCollection)
                {
                    this.DropDownList_DefaultCurrency.Items.Add(new ListItem(CurrencyObj.DisplayName, CurrencyObj.InternalID));
                    if (CurrencyObj.InternalID.CompareTo(SelectedCurrency) == 0)
                    {
                        this.DropDownList_DefaultCurrency.Items[(this.DropDownList_DefaultCurrency.Items.Count - 1)].Selected = true;

                        if (ExRateCollection != null)
                        {
                            foreach (MasterBase ExRateObj in ExRateCollection)
                            {
                                Currency CurExRateCurrency = (Currency)ExRateObj;
                                if (CurExRateCurrency.InternalID.CompareTo(SelectedCurrency) == 0)
                                {
                                    this.TextBox_DefaultCurrencyRate.Text = CurExRateCurrency.ExchangeRate.ToString();
                                }
                            }
                        }                                                
                    }                    
                }
            }            
        }        
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Remarks.Text = CurLanguageFactory.DisplayValue("Remarks");

                this.Label_Category.Text = CurLanguageFactory.DisplayValue("ItemCategory");
                this.Label_EmployeeID.Text = CurLanguageFactory.DisplayValue("ItemEmployeeID");
                this.Label_Name.Text = CurLanguageFactory.DisplayValue("ItemName");
                this.Label_ProfitCenter.Text = CurLanguageFactory.DisplayValue("ItemProfitCenter");
                this.Label_Purpose.Text = CurLanguageFactory.DisplayValue("ItemPurpose");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("ButtonSubmit");

                this.RadioButtonList_Category.Items[0].Text = CurLanguageFactory.DisplayValue("ItemGeneral");
                this.RadioButtonList_Category.Items[1].Text = CurLanguageFactory.DisplayValue("ItemEntertainment");
                // Thang Nguyen added 22/03/2013
                //this.RadioButtonList_Category.Items[2].Text = CurLanguageFactory.DisplayValue("ItemPACEMarketingEvent");

                this.Response_Error = CurLanguageFactory.DisplayValue("UnExpectedError");
                this.ValidatePurpose = CurLanguageFactory.DisplayValue("ValidatePurpose");
                this.ValidateCategory = CurLanguageFactory.DisplayValue("ValidateCategory");       
         
                this.Label1.Text = CurLanguageFactory.DisplayValue("Label1");
                this.Label_Country.Text = CurLanguageFactory.DisplayValue("Country");
                this.Label_DefaultCurrencyRate.Text = CurLanguageFactory.DisplayValue("DefaultCurrencyRate");
                // Thang Nguyen added 22/03/2013
                this.Label_DefaultProjectID.Text = CurLanguageFactory.DisplayValue("DefaultProjectID");

                this.CheckBox_ImportCreditCard.Text = CurLanguageFactory.DisplayValue("ImportCreditCard");
                this.Label3.Text = CurLanguageFactory.DisplayValue("Label3");
                this.WarningMessage = CurLanguageFactory.DisplayValue("WarningMessage");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesMain.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
    }
    #endregion

    #region DataValidate

    protected bool DataValidate()
    {
        bool smooth = true;
        StringBuilder MessageBuilder = new StringBuilder("<ul>");

        if (this.TextBox_Purpose.Text.Trim().Length == 0)
        {
            smooth = false;
            MessageBuilder.AppendLine("<li>" + this.ValidatePurpose + "</li>");
        }

        if (this.RadioButtonList_Category.SelectedIndex == -1)
        {
            smooth = false;
            MessageBuilder.AppendLine("<li>" + this.ValidateCategory + "</li>");
        }

        MessageBuilder.AppendLine("</ul>");

        if (!smooth)
        {
            this.ShowErrorMessage(MessageBuilder.ToString());
        }

        return smooth;
    }

    #endregion

    #endregion

    #region Javascripts

    #region GenerateExchangeRate
    public void GenerateExchangeRate()
    {
        MasterBaseCollection ExchangeRateFigures = null;
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");

        using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
        {
            ExchangeRateFigures = CurCurrencyManager.GetLatestExchangeRate(this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency);
            if (ExchangeRateFigures != null)
            {
                JSBuilder.AppendLine("var LocalCurrency = '" + this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency.InternalID + "';");
                JSBuilder.AppendLine("var TargetCurrency = new Array(" + ExchangeRateFigures.Count + ");");
                JSBuilder.AppendLine("var ExchangeRate = new Array(" + ExchangeRateFigures.Count + ");");

                ExchangeRateFigures.Sort();
                for (int x = 0; x < ExchangeRateFigures.Count; x++)
                {
                    Currency CurCurrency = (Currency)ExchangeRateFigures[x];

                    JSBuilder.AppendLine("TargetCurrency[" + x + "] = '" + CurCurrency.InternalID + "';");
                    JSBuilder.AppendLine("ExchangeRate[" + x + "] = " + Convert.ToDecimal(CurCurrency.ExchangeRate) + ";");
                }

            }
            else
            {
                this.CurLogManager.LogError("[GonzalesMyDraftDetail.GenerateExchangeRate] : " + CurCurrencyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
            }
        }

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GenerateExchangeRate"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GenerateExchangeRate", JSBuilder.ToString());
        }
    }
    #endregion

    #region GenerateWarningMessage
    public void GenerateWarningMessage()
    {
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");
        JSBuilder.AppendLine("var WarningMessage = '" + this.WarningMessage + "';");

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GenerateWarningMessage"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GenerateWarningMessage", JSBuilder.ToString());
        }
    }
    #endregion

    #region GenerateCountryCurrencyRefference

    public void GenerateCountryCurrencyRefference()
    {
        using (CountryManager CurManager = new CountryManager(this.CurrentPrivateSession))
        {
            MasterBaseCollection Countries = CurManager.GetAllCountry();

            if (Countries != null)
            {
                StringBuilder JSBuilder = new StringBuilder();
                JSBuilder.AppendLine("<script language='javascript'>");

                JSBuilder.AppendLine("var CountryArray = new Array(" + Countries.Count + ");");
                JSBuilder.AppendLine("var CurrencyArray = new Array(" + Countries.Count + ");");

                for (int x = 0; x < Countries.Count; x++)
                {
                    Country CurCountry = (Country)Countries[x];

                    JSBuilder.AppendLine("CountryArray[" + x + "] = '" + CurCountry.InternalID + "';");
                    JSBuilder.AppendLine("CurrencyArray[" + x + "] = '" + CurCountry.CountryCurrency.InternalID + "';");
                }

                JSBuilder.AppendLine("</script>");

                // done, generate on the page
                if (!this.ClientScript.IsClientScriptBlockRegistered("GenerateCountryCurrencyRefference"))
                {
                    this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GenerateCountryCurrencyRefference", JSBuilder.ToString());
                }
            }
        
        }
    }

    #endregion

    #endregion

    protected void RadioButtonList_Category_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (((RadioButtonList)sender).SelectedValue.Equals("2"))
        {
            TextBox_DefaultProjectID.Visible = true;
            Label_DefaultProjectID.Visible = true;
        }
        else
        {
            TextBox_DefaultProjectID.Visible = false;
            Label_DefaultProjectID.Visible = false;
            TextBox_DefaultProjectID.Text = string.Empty;
        }
    }
}
